﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.Common;
using UFC.DBUtility;
using System.Xml;


namespace MESQualityHistoryRecord
{
    public class SendFirstIdentifyProductToQms
    {
        public void RunFirstIdentifyProductSync()
        {
            DataTable mydt = GetFirstIdentifyProduct();
            if (mydt == null || mydt.Rows.Count <= 0)
            {
                LogHelp.WriteLog("没有可处理的控制点记录");
            }

            foreach (DataRow row in mydt.Rows)
            {
                var strList = GetDictionary(row);
                var strName = string.Empty;
                var strMethod = string.Empty;
                if (row["IDENTIFYTYPE"].ToString() == "1")//首件鉴定到达控制点接口
                {
                    strName = "首件鉴定到达控制点接口";
                    strMethod = "firstThingAuthArrive";
                }
                if (row["IDENTIFYTYPE"].ToString() == "2")//产品质量评审到达控制点接口
                {
                    strName = "产品质量评审到达控制点接口";
                    strMethod = "pushQaProductReviewDirArrive";
                }
                if (row["IDENTIFYTYPE"].ToString() == "3")//工艺评审到达控制点接口
                {
                    strName = "工艺评审到达控制点接口";
                    strMethod = "pushCraftReviewDirArrive";
                }
                var resQxml = CreateXMLForFirstIdentifyProductToQms(strList, strMethod);//组装xml
                LogHelp.WriteLog(strName + "推送XMl:" + resQxml);
                NewMesToQms.unifiedFunApi mtq = new NewMesToQms.unifiedFunApi();
                var resPxml = mtq.mesToQmsAPI(resQxml);
                LogHelp.WriteLog(strName + "返回XMl:" + resPxml);
                Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["FIRSTTHINGAUTHDIRID"].ToString ()},{"RecordType","QMS_"+strMethod},
                        {"ContainerID",""},{"ContainerName",""},
                        {"ProductName",row["componentsImgNo"].ToString()},{"WorkflowStepName",""},
                        {"SendXml",resQxml},{"ResXml",resPxml}
                    };
                XmlDocument myxml = new XmlDocument();
                myxml.LoadXml(resPxml);
                string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                myxml.LoadXml(xml);
                string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//
                if (!string.IsNullOrWhiteSpace(success) && success == "S")
                {
                    recordPara.Add("IsSuccess", "0");//成功
                }
                else
                {
                    recordPara.Add("IsSuccess", "1");//失败
                    LogHelp.WriteLog(message);
                }
                OracleDAL.InserOtherSystemRecord(recordPara);
            }
        
        }
        /// <summary>
        /// 获取未发送的到达控制点
        /// </summary>
        /// <returns></returns>
        public DataTable GetFirstIdentifyProduct() {
            try
            {
                string strSql = @" SELECT FIRSTIDENTIFYPRODUCTID firstThingAuthDirId,e.employeename handleEmployeeNo,DRAWINGNO componentsImgNo,
                                q.PRODUCTNAME	componentsName,VERSIONNO craftVersionNo,IDENTIFYTYPE,
                                FIRSTIDENTIFYPRODUCTID qaProductReviewDirId,DRAWINGNO componentsNo,
                                FIRSTIDENTIFYPRODUCTID craftReviewDirId,DRAWINGNO reviewFileNo,q.PRODUCTNAME fileName
                                FROM FirstIdentifyProduct q
                                 LEFT JOIN (
                                	SELECT wm_concat(e.employeename) employeename,s.FACTORYID from roledef ro 
				                    left JOIN employeerole erl ON erl.roleid=ro.roleid
				                    left JOIN employee e on e.employeeid=erl.employeeid
				                    LEFT JOIN SESSIONVALUES s ON s.SESSIONVALUESID =e.SESSIONVALUESID 
				                    where ro.rolename like '%控制点解除处理人员' GROUP BY s.FACTORYID
                                ) e ON e.FACTORYID=q.FACTORYID
                                left join WritetoOtherSystem ws on ws.parentid=q.FIRSTIDENTIFYPRODUCTID and ws.recordtype IN('QMS_firstThingAuthArrive','QMS_pushQaProductReviewDirArrive','QMS_pushCraftReviewDirArrive')
                                WHERE e.employeename IS NOT NULL and ws.parentid is null and rownum<500";
                DataSet myDS = OracleHelper.Query(strSql);
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("控制点到达获取", e);
                return null;
            }
        }

        /// <summary>
        /// 获取Xml字典
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetDictionary(DataRow row)
        {
            var strList = new Dictionary<string, string>();
            var keys = @"firstThingAuthDirId,handleEmployeeNo,componentsImgNo,componentsName,craftVersionNo";
            if (row["IDENTIFYTYPE"].ToString() == "2")
            {
                keys = "qaProductReviewDirId,handleEmployeeNo,componentsNo,componentsName";
            }
            if (row["IDENTIFYTYPE"].ToString() == "3")
            {
                keys = "craftReviewDirId,handleEmployeeNo,reviewFileNo,fileName";
            }
            foreach (var key in keys.Split(','))
            {
                if (row.Table.Columns.Contains(key))
                {
                    strList.Add(key, row[key].ToString());
                }
                else
                {
                    strList.Add(key, "");
                }
            }
            return strList;
        }
        /// <summary>
        /// 生成xml
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        private string CreateXMLForFirstIdentifyProductToQms(Dictionary<string, string> strList, string qmsFunName)
        {
            try
            {
                #region MyRegion
                    XmlDocument doc = new XmlDocument();
                    doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
                    XmlNode ReqNode = doc.CreateElement("ReqMsg");
                    XmlNode headerNode = doc.CreateElement("header");
                    XmlNode senderNode = doc.CreateElement("sendSysName");
                    senderNode.InnerText = "APP_MES";
                    XmlNode rcvNode = doc.CreateElement("rcvSysName");
                    rcvNode.InnerText = "APP_QMS";
                    XmlNode extNode = doc.CreateElement("extConfig");
                    extNode.AppendChild(doc.CreateElement("isReTry"));
                    extNode.LastChild.InnerText = "false";
                    extNode.AppendChild(doc.CreateElement("FunName"));
                    extNode.LastChild.InnerText = "MES_Send_Service";
                    headerNode.AppendChild(senderNode);
                    headerNode.AppendChild(rcvNode);
                    headerNode.AppendChild(extNode);
                    ReqNode.AppendChild(headerNode);

                    XmlNode root = doc.CreateElement("root");
                    XmlNode qmsFun = doc.CreateElement("qmsFunName");
                    qmsFun.InnerText = qmsFunName;//具体调用方法
                    root.AppendChild(qmsFun);

                    XmlNode documentNode = doc.CreateElement("document");
                    ReqNode.AppendChild(documentNode);

                    XmlNode qmsDocument = doc.CreateElement("qmsDocument");//具体业务内容
                #endregion
                foreach (KeyValuePair<string, string> _key in strList)
                {
                    XmlNode mainData = doc.CreateElement(_key.Key);
                    mainData.InnerText =_key.Value;
                    qmsDocument.AppendChild(mainData);
                }
                root.AppendChild(qmsDocument);
                documentNode.AppendChild(doc.CreateCDataSection("<root>"+root.InnerXml+"</root>"));
                doc.AppendChild(ReqNode);
                return doc.InnerXml;
            }
            catch (Exception e)
            {
                LogHelp.WriteError("质量问题提起XML", e);
                return string.Empty;
            }
        }

        private void UpdateFirstIdentifyProduct(string ID)
        {
            try
            {
                string updateSql = string.Format(@"UPDATE FirstIdentifyProduct SET IsSendErp='1' WHERE FIRSTIDENTIFYPRODUCTID='{0}' ", ID);
                OracleHelper.ExecuteSql(updateSql);
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("控制点解除更新失败：" + ex.Message);
            }
        }
    
    }
}
